<template>
  <div class="container">
    <el-card class="login-card" shadow="hover">
      <div class="content">
        <!-- Step 1: 微信二维码登录页面 -->
        <template v-if="step === 1">
          <div class="QR-code">
            <div class="QR-code-title">
              <div class="header">
                <div class="brand">
                  <img src="../assets/xwimg/logo.png" alt="" />
                </div>
              </div>

              <h2>微信登录</h2>
              <div class="tip">微信扫描 > 关注公众号 > 即可登录</div>
            </div>
            <img :src="codeimg" alt="微信二维码" class="qr-img" />
            <div class="other-options">
              <p>更多登录方式：</p>
              <div class="option-buttons">
                <el-button type="text" @click="step = 2"
                  >账号密码登录</el-button
                >
                <el-button type="text" @click="step = 3">手机号登录</el-button>
              </div>
            </div>
          </div>
        </template>

        <!-- Step 2: 账号密码登录页面 - 修改后 -->
        <template v-else-if="step === 2">
          <div class="login-form">
            <div class="header">
              <div class="brand">
                <img src="../assets/xwimg/logo.png" alt="" />
              </div>
            </div>

            <div class="tip">
              <h2>用户名&密码登录</h2>
              <div class="tip-text">用户名及密码是您在个人中心自行设置的</div>
            </div>

            <el-form style="margin-top: 10%" @keyup.enter="loginByAccount">
              <el-form-item>
                <el-input
                  v-model="form.username"
                  class="input-field"
                  placeholder="用户名"
                  @keyup.enter="loginByAccount"
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-input
                  v-model="form.password"
                  type="password"
                  class="input-field"
                  placeholder="密码"
                 
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-button
                type="primary"
                class="login-btn"
                :loading="loggingIn"
                @click="loginByAccount"
              >
                登录
              </el-button>

              <div class="other-options" style="margin-top: 10%">
                <p>更多登录方式：</p>
                <div class="option-buttons">
                  <el-button type="text" @click="step = 1">微信登录</el-button>
                  <el-button type="text" @click="step = 3"
                    >手机号登录</el-button
                  >
                </div>
              </div>
            </el-form>
          </div>
        </template>

        <!-- Step 3: 手机号注册/登录 -->
        <template v-else>
          <div class="login-form">
            <div class="header">
              <div class="brand">
                <img src="../assets/xwimg/logo.png" alt="" />
              </div>
            </div>

            <div class="tip">
              <h2>手机短信登录</h2>
              <div class="tip-text">手机号码为您在个人中心绑定过的手机号码</div>
            </div>

            <el-form style="margin-top: 10%">
              <el-form-item style="">
                <el-input
                  v-model="form.phone"
                  class="input-field"
                  placeholder="手机号"
                  maxlength="11"
                >
                  <template #prefix>
                    <el-icon><PhoneFilled /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <div class="code-input">
                  <el-input
                    v-model="form.code"
                    class="input-field code-box"
                    placeholder="验证码"
                    maxlength="4"
                  >
                    <template #prefix>
                      <el-icon><Lock /></el-icon>
                    </template>
                  </el-input>
                  <el-button
                    :disabled="countdown > 0 || gettingCode"
                    @click="getCode"
                    class="code-btn"
                  >
                    {{ countdown > 0 ? countdown + "s" : "获取验证码" }}
                  </el-button>
                </div>
              </el-form-item>

              <el-button
                type="primary"
                class="login-btn"
                :loading="loggingIn"
                @click="login"
              >
                登录
              </el-button>

              <div class="other-options" style="margin-top: 10%">
                <p>更多登录方式：</p>
                <div class="option-buttons">
                  <el-button type="text" @click="step = 1">微信登录</el-button>
                  <el-button type="text" @click="step = 2"
                    >账号密码登录</el-button
                  >
                </div>
              </div>
            </el-form>
          </div>
        </template>
      </div>

      <div class="agreement">
        登录即代表你已阅读并同意
        <span class="policy-link" @click="showUserAgreement">《用户协议》</span>
        和
        <span class="policy-link" @click="showPrivacyPolicy">《隐私政策》</span>
      </div>
    </el-card>

    <el-dialog v-model="yinsi" title="隐私政策" width="60%" center>
      <describe></describe>
      <template #footer>
        <div class="dialog-footer" style="padding: 20px">
          <el-button @click="yinsi = false">关闭</el-button>
          <el-button type="primary" @click="yinsi = false"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="yonghu" title="用户协议" width="60%" center>
     <UserAgreement></UserAgreement>
      <template #footer>
        <div class="dialog-footer" style="padding: 20px">
          <el-button @click="yonghu = false">关闭</el-button>
          <el-button type="primary" @click="yonghu = false"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { PhoneFilled, Lock, User } from '@element-plus/icons-vue'
import { loginApi } from '../api/login.js'
import { useAuthStore } from '../stores'
// 将本地图片导入重命名为localCodeImg
import localCodeImg from '../assets/xwimg/news.jpg'
import describe from './components/describe.vue'
import UserAgreement from './components/UserAgreement.vue'

const router = useRouter()
const authStore = useAuthStore()
const yinsi = ref(false)
const yonghu=ref(false)
const step = ref(1)

const form = ref({
  phone: '',
  code: '',
  username: '',
  password: '',
  position: 'login',
})

const codeimg = ref(localCodeImg)
const code = ref('')
const countdown = ref(0)
const timer = ref(null)
const qrTimer = ref(null)
const gettingCode = ref(false)
const loggingIn = ref(false)

const showUserAgreement = () => {
 
  yonghu.value = true  
}
const showPrivacyPolicy = () => {
  yinsi.value = true
}

// 倒计时
const startCountdown = () => {
  if (timer.value) clearInterval(timer.value)
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}

// 获取短信验证码
const getCode = async () => {
  if (!/^\d{11}$/.test(form.value.phone)) {
    ElMessage.error('请输入正确的11位手机号')
    return
  }
  gettingCode.value = true
  try {
    const res = await loginApi.getMsg({ phone: form.value.phone, position: form.value.position })
    const sec = res.data.getMsg.timer
    countdown.value = sec
    ElMessage.success('验证码已发送')
    startCountdown()
  } catch (err) {
    ElMessage.error(err.message || '验证码发送失败')
  } finally {
    gettingCode.value = false
  }
}

// 手机号验证码登录
const login = async () => {
  if (!/^\d{11}$/.test(form.value.phone)) {
    ElMessage.error('请输入正确的11位手机号')
    return
  }
  if (!/^\d{4}$/.test(form.value.code)) {
    ElMessage.error('请输入4位验证码')
    return
  }
  loggingIn.value = true
  try {
    const res = await loginApi.login(form.value)
    if (res.data.loginByMsg?.token) {
      authStore.login({
        token: res.data.loginByMsg.token,
        userInfo: res.data.loginByMsg
      })
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      throw new Error(res.data.message || '登录失败')
    }
  } catch (err) {
    ElMessage.error(err.message || '登录失败')
  } finally {
    loggingIn.value = false
  }
}

// 账号密码登录
const loginByAccount = async () => {
  if (!form.value.username || !form.value.password) {
    ElMessage.error('请输入账号和密码')
    return
  }
  loggingIn.value = true
  try {
    const res = await loginApi.loginByAccount({
      userName: form.value.username,
      pwd: form.value.password
    })
    if (res.data.token) {
      authStore.login({
        token: res.data.loginByPwd.token,
        userInfo: res.data.loginByPwd
      })
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(res.msg || '登录失败')
    }
  } catch (err) {
    ElMessage.error(err.msg || '登录失败')
  } finally {
    loggingIn.value = false
  }
}

// 获取二维码并轮询登录状态
onMounted(() => {
  loginApi.getQrCode().then(res => {
    // 成功获取远程二维码时更新图片
    codeimg.value = res.data.getLoginPic.loginPic
    code.value = res.data.getLoginPic.uniqueId

    qrTimer.value = setInterval(() => {
      loginApi.checkLoginStatus({ uniqueId: code.value }).then(res => {
        if (res.data.loginByWx?.token) {
          clearInterval(qrTimer.value)
          authStore.login({
            token: res.data.loginByWx.token,
            userInfo: res.data.loginByWx
          })
          ElMessage.success('扫码登录成功')
          router.push('/')
        }
      })
    }, 5000)
  }).catch(() => {
    // 获取失败时保持本地默认图片
    ElMessage.warning('二维码加载失败，使用默认二维码')
  })
})

onUnmounted(() => {
  if (timer.value) clearInterval(timer.value)
  if (qrTimer.value) clearInterval(qrTimer.value)
})
</script>

<style lang="scss" scoped>
.container {
  background: url("../assets/xwimg/bg.png") center/cover no-repeat;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}
.login-card {
  width: 100%;
  max-width: 1200px;
  height: 85%;
  min-height: 600px;
  border-radius: 30px;
  position: relative;
  overflow: hidden;
}
.content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 60px 30px;
  box-sizing: border-box;
}

.login-form {
  width: 100%;
  max-width: 450px;
  padding: 20px;
  box-sizing: border-box;
}
.header {
  margin-bottom: 10px;
  text-align: center;
  .welcome {
    font-size: 24px;
    color: #333;
    margin: 0 0 10px;
    font-weight: bold;
  }
  .brand img {
    height: 40px;
    width: auto;
    max-width: 200px;
  }
}
.tip {
  text-align: center;
  margin-bottom: 30px;
  h2 {
    color: #0080d1;
    margin-bottom: 8px;
    font-size: 20px;
  }
  .tip-text {
    color: rgba(21, 22, 24, 0.7);
    font-size: 14px;
  }
}
.input-field {
  height: 50px;
  border-radius: 12px;
  margin-bottom: 20px;
  font-size: 16px;

  :deep(.el-input__prefix) {
    display: flex;
    align-items: center;
    padding-left: 15px;
  }
}
.code-input {
  display: flex;
  align-items: center;
  gap: 10px;
  .code-box {
    flex: 1;
  }
  .code-btn {
    height: 50px;
    min-width: 120px;
    border: none;
    font-size: 16px;
    color: #0080d1;
    background: #f5f7fa;
    border-radius: 12px;
    transition: all 0.3s;

    &:hover {
      background: #e6f3ff;
    }

    &:disabled {
      color: #999;
      background: #f5f5f5;
      cursor: not-allowed;
    }
  }
}
.login-btn {
  width: 100%;
  height: 50px;
  border-radius: 12px;
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 2px;
}
.QR-code {
  width: 100%;
  max-width: 450px;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;

  .QR-code-title {
    // margin-bottom: 20px;
    h2 {
      font-size: 20px;
      margin: 0 0 10px;
      color: #0080d1;
    }
    .tip {
      color: #666;
      font-size: 16px;
    }
  }
  .qr-img {
    width: 100%;
    max-width: 280px;
    height: auto;
    margin: 0 auto 20px;
    border: 10px solid #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}
.agreement {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: #999;
  text-align: center;
  font-size: 14px;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;

  .policy-link {
    color: #0080d1;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;
  }
  .policy-link:hover {
    color: #005a9e;
  }
}
.other-options {
  margin-top: 30px;
  font-size: 16px;
  color: #666;
  text-align: center;

  p {
    margin-bottom: 10px;
    font-weight: 500;
  }

  .option-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    flex-wrap: wrap;

    .el-button {
      font-size: 16px;
      color: #0080d1;
      padding: 8px 15px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        background: #e6f3ff;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    border-radius: 20px;
    height: auto;
  }

  .content {
    padding: 40px 15px;
  }

  .header .welcome {
    font-size: 20px;
  }

  .tip h2 {
    font-size: 18px;
  }

  .input-field,
  .code-btn {
    height: 46px;
  }

  .qr-img {
    max-width: 250px !important;
  }

  .agreement {
    position: relative;
    margin-top: 30px;
    bottom: auto;
    left: auto;
    transform: none;
    padding: 0;
  }

  .other-options .option-buttons {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .login-card {
    border-radius: 15px;
  }

  .content {
    padding: 30px 10px;
  }

  .header .welcome {
    font-size: 18px;
  }

  .tip h2 {
    font-size: 16px;
  }

  .input-field,
  .code-btn {
    height: 42px;
    font-size: 14px;
  }

  .qr-img {
    max-width: 200px !important;
  }

  .login-btn {
    height: 46px;
    font-size: 16px;
  }

  .agreement {
    font-size: 12px;
  }
}


.code-input {
  display: flex;
  align-items: stretch; /* 子元素同高 */
  gap: 10px;
  margin-bottom: 20px; /* 保留和其它行的间距 */
}

/* 去掉验证码输入框的专属下边距 */
.code-input .input-field {
  margin-bottom: 0 !important;
}

/* 强制内层 el-input 高度 */
.code-input .el-input__inner {
  height: 50px; /* 跟全局输入框保持一致 */
}

/* 按钮同样填满高度，并让文字垂直居中 */
.code-input .code-btn {
  height: 50px;
  width: 183px;
  line-height: 50px;
  padding: 0 16px; /* 根据需要调整左右内边距 */
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.login-form {
  padding: 20px 0;
}
</style>